package org.spring.springboot.exception.common.selfex;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.springboot.exception.common.ascept.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

/**
 * 统一错误码异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = BusinessException.class)
    public Result<String> BusinessExceptionHandler(BusinessException exception) throws IOException {
        logger.info(exception.toString());
        Result<String> result = new Result<String>();
        result.setMsg(exception.getMessage());
        result.setStatus(Integer.parseInt(exception.getCode()));
        return result;
    }

    @ExceptionHandler(value = Exception.class)
    public Result<String> OtherExceptionHandler(Exception e) throws IOException {
        
        Result<String> result = new Result<String>();
        	
        if (e instanceof StringIndexOutOfBoundsException) {
        	logger.error(e.toString());
        } else if (e instanceof NullPointerException) {
        	logger.error(e.toString());
        } else {
        	logger.error(e.toString());
        }
        result.setStatus(300005);
        result.setMsg("系统异常");
        return result;
    }
}
